/*
 * Copyright 2011 Clean GWT
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.cleangwt.user.cellview.client;

import com.cleangwt.json.client.SimpleObject;
import com.google.gwt.cell.client.ButtonCell;
import com.google.gwt.cell.client.Cell.Context;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.cellview.client.Column;

/**
 * A {@link Column} with {@link ButtonCell} used to render a button with action.
 * 
 * @author Jess
 * @version 1.0
 * @since 1.0
 */
public class ActionColumn extends Column<SimpleObject, String> {

  /**
   * Used to handler table actions.
   */
  public interface TableActionHandler {
    void onTableAction(String action, int index, SimpleObject rowData);
  }

  private String action;
  private String text;

  /**
   * Creates an action column with the given text and {@link TableActionHandler}.
   * 
   * @param text the text
   * @param handler the action handler
   */
  public ActionColumn(String text, TableActionHandler handler) {
    this(text, null, handler);
  }

  /**
   * Creates an action column with the given text, action and {@link TableActionHandler}.
   * 
   * @param text the text
   * @param action the action identity
   * @param handler the action handler
   */
  public ActionColumn(String text, String action, final TableActionHandler handler) {
    super(new ButtonCell());
    this.text = text;
    this.action = action;
    super.setFieldUpdater(new FieldUpdater<SimpleObject, String>() {

      @Override
      public void update(int index, SimpleObject object, String value) {
        handler.onTableAction(value, index, object);
      }

    });
  }

  @Override
  public String getValue(SimpleObject object) {
    return action;
  }

  @Override
  public void render(Context context, SimpleObject object, SafeHtmlBuilder sb) {
    this.getCell().render(context, text, sb);
  }

  /**
   * @deprecated filed updater already set in constructor.
   */
  @Deprecated
  @Override
  public void setFieldUpdater(FieldUpdater<SimpleObject, String> fieldUpdater) {
    throw new UnsupportedOperationException();
  }
}
